package com.sj.controller;

import cn.hutool.core.map.MapUtil;
import com.sj.common.lang.ApiResult;
import com.sj.common.lang.ResultInfo;
import com.sj.interceptor.AuthCheck;
import com.sj.oss.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-03-12
 * Time: 下午 15:35
 * Description: 文件模块
 *
 * @author xiaoqi
 * @since 2022-03-12
 */
@RestController
@RequestMapping("/file")
@Api(tags = "文件模块")
public class FileController {
    @Autowired
    private OssService ossService;

    @PostMapping("/upload")
    @ApiOperation(value = "单文件上传接口")
    @AuthCheck
    public ApiResult upload(@RequestParam("file") MultipartFile file) {
        String url = ossService.upload(file);
        return ApiResult.success(ResultInfo.SUCCESS,
                MapUtil.builder()
                        .put("url", url)
                        .build());
    }

    @PostMapping("/uploads")
    @ApiOperation(value = "多文件上传接口")
    @AuthCheck
    public ApiResult uploads(@RequestParam("files") MultipartFile[] files) {
        List<String> urls = Arrays.asList(files).stream().map(file -> ossService.upload(file)).collect(Collectors.toList());
        return ApiResult.success(ResultInfo.SUCCESS,
                MapUtil.builder()
                        .put("url", urls)
                        .build());
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "文件删除接口")
    @AuthCheck
    public ApiResult delete(@RequestParam("fileName") @ApiParam(name = "fileName", value = "文件名") String fileName) {
        boolean result = ossService.deleteFile(fileName);
        if (result) {
            return ApiResult.success(ResultInfo.SUCCESS);
        }
        return ApiResult.error(ResultInfo.ERROR);
    }

    @DeleteMapping("/delete/batches")
    @ApiOperation(value = "文件批量删除接口")
    @AuthCheck
    public ApiResult deleteInBatches(@RequestParam("fileNames") @ApiParam(name = "fileNames", value = "多个文件名") List<String> fileNames) {
        boolean result = ossService.deleteInBatches(fileNames);
        if (result) {
            return ApiResult.success(ResultInfo.SUCCESS);
        }
        return ApiResult.error(ResultInfo.ERROR);
    }
}